package com.dhecp.project.quartz.task;

import com.alibaba.fastjson.JSON;
import com.dhecp.core.utils.DateUtils;
import com.dhecp.project.api.domain.ApiResponse;
import com.dhecp.project.api.service.ApiAmazonService;
import com.dhecp.project.api.service.ApiLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName ApiAmazonTask
 * @Description TODO
 * @Author alula
 * @Date 2022-09-26 9:33
 */
@Component("apiAmazonTask")
public class ApiAmazonTask {

    private static final Logger logger = LoggerFactory.getLogger(ApiAmazonTask.class);
    //亚马逊系统名称
    private static final String AMAZON_SYSTEM_NAME = "Amazon";

    @Autowired
    private ApiLogService apiLogService;

    @Autowired
    private ApiAmazonService apiAmazonService;

    /**
     * 定时获取亚马逊订单信息(3:00运行)
     */
    public void getAmazonOrder()
    {
        try {
            String type = "GetAmazonOrderInfo";
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("authorizeState","已授权");
            Date startTime = DateUtils.firstAndLateData(-14,0,0,0,0,0,0,null);//当前时间之前14天
            Date endTime = DateUtils.firstAndLateData(0,0,59,59,23,23,0,null);//当天23：59:59
            int insertLogId = apiLogService.addApiLog(AMAZON_SYSTEM_NAME,type,"定时获取任务获取亚马逊订单信息，条件queryParams：" + JSON.toJSONString(queryParams), "",0, "");
            ApiResponse apiResponse = apiAmazonService.getAllAmazonOrderInfo(insertLogId, AMAZON_SYSTEM_NAME, type, queryParams,startTime,2,endTime);
            if (apiResponse.getCode() == 500){
                apiLogService.updateApiLog(insertLogId, AMAZON_SYSTEM_NAME, type, "定时获取任务获取亚马逊订单信息，条件queryParams：" + JSON.toJSONString(queryParams), "ECP_API定时获取亚马逊店铺订单出错[取前14天数据]，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }

        }catch (Exception ex){
            logger.error("ECP_API定时获取亚马逊店铺订单出错[取前14天数据]，错误信息为：" + ex.getMessage());
        }
    }

    /**
     * 获取亚马逊订单信息(每天9：00点运行)
     */
    public void getAmazonOrder2()
    {
        try {
            String type = "GetAmazonOrderInfo2";
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("authorizeState","已授权");
            Date startTime = DateUtils.firstAndLateData(-1,0,0,0,0,0,0,null);//当前时间之前1天
            Date endTime = DateUtils.firstAndLateData(0,0,59,59,23,23,0,null);//当天23：59:59
            int insertLogId = apiLogService.addApiLog(AMAZON_SYSTEM_NAME,type,"定时获取任务获取亚马逊订单信息，条件queryParams：" + JSON.toJSONString(queryParams), "",0, "");
            ApiResponse apiResponse = apiAmazonService.getAllAmazonOrderInfo(insertLogId, AMAZON_SYSTEM_NAME, type, queryParams,startTime,3,endTime);
            if (apiResponse.getCode() == 500){
                apiLogService.updateApiLog(insertLogId, AMAZON_SYSTEM_NAME, type, "定时获取任务获取亚马逊订单信息，条件queryParams：" + JSON.toJSONString(queryParams), "ECP_API定时获取亚马逊店铺订单出错[取前一天数据]，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }

        }catch (Exception ex){
            logger.error("ECP_API定时获取亚马逊店铺订单出错[取前一天数据]，错误信息为：" + ex.getMessage());
        }
    }

    /**
     * 获取亚马逊订单实时订单,判断是否有权限，改变店铺授权失败状态
     */
    public void getAmazonShop()
    {
        try {
            String type = "GetAmazonShop";
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("authorizeState","已授权");
            Calendar calendar = new GregorianCalendar();
            calendar.add(Calendar.DATE, -1);//每天9点钟运行时，取当前时间之前1天的数据
            Date startTime = calendar.getTime();
            startTime.setHours(0);
            startTime.setMinutes(0);
            startTime.setSeconds(0);
            int insertLogId = apiLogService.addApiLog(AMAZON_SYSTEM_NAME,type,"ECP_API定时获取亚马逊店铺是否失效出错，条件queryParams：" + JSON.toJSONString(queryParams), "",0, "");
            ApiResponse apiResponse = apiAmazonService.getAmazonShop(AMAZON_SYSTEM_NAME, type, queryParams,startTime,3);
            if (apiResponse.getCode() == 500){
                apiLogService.updateApiLog(insertLogId, AMAZON_SYSTEM_NAME, type, "ECP_API定时获取亚马逊店铺是否失效出错，条件queryParams：" + JSON.toJSONString(queryParams), "ECP_API定时获取亚马逊店铺订单出错[取前一天数据]，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }

        }catch (Exception ex){
            logger.error("ECP_API定时获取亚马逊店铺出错，错误信息为：" + ex.getMessage());
        }
    }

    /**
     * 定时获取亚马逊店铺销售产品信息(每晚22：30运行)
     */
    public void getAmazonShopProduct()
    {
        try {
            String type = "GetAmazonShopProductInfo";
            Map<String, Object> queryParams = new HashMap<>();
            int insertLogId = apiLogService.addApiLog(AMAZON_SYSTEM_NAME,type,"queryParams：" + JSON.toJSONString(queryParams), "",0, "");
            ApiResponse apiResponse = apiAmazonService.getAllAmazonShopProductInfo(insertLogId, AMAZON_SYSTEM_NAME, type, queryParams);
            if (apiResponse.getCode() == 500){
                apiLogService.updateApiLog(insertLogId, AMAZON_SYSTEM_NAME, type, "queryParams：" + JSON.toJSONString(queryParams), "ECP_API定时获取亚马逊店铺商品相关信息出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
        }catch (Exception ex){
            logger.error("ECP_API定时获取亚马逊店铺商品相关信息出错，错误信息为：" + ex.getMessage());
        }
    }

    /**
     * 定时获取亚马逊店铺销售产品信息(每晚23：10运行)
     */
    public void getAmazonShopProductPriceReport()
    {
        try {
            String type = "GetAmazonShopProductPriceReport";
            Map<String, Object> queryParams = new HashMap<>();
            int insertLogId = apiLogService.addApiLog(AMAZON_SYSTEM_NAME,type,"queryParams：" + JSON.toJSONString(queryParams), "",0, "");
            ApiResponse apiResponse = apiAmazonService.getAllAmazonShopProductPriceReport(insertLogId, AMAZON_SYSTEM_NAME, type, queryParams);
            if (apiResponse.getCode() == 500){
                apiLogService.updateApiLog(insertLogId, AMAZON_SYSTEM_NAME, type, "queryParams：" + JSON.toJSONString(queryParams), "ECP_API定时获取亚马逊店铺商品价格报表信息出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
        }catch (Exception ex){
            logger.error("ECP_API定时获取亚马逊店铺商品价格报表信息出错，错误信息为：" + ex.getMessage());
        }
    }

    /**
     * 定时获取亚马逊店铺商品销售流量报表信息(每晚0：30取前一天运行)
     */
    public void getAmazonSalesTrafficReport()
    {
        try {
            String type = "GetAmazonSalesTrafficReport";
            Map<String, Object> queryParams = new HashMap<>();
            int insertLogId = apiLogService.addApiLog(AMAZON_SYSTEM_NAME,type,"queryParams：" + JSON.toJSONString(queryParams), "",0, "");
            ApiResponse apiResponse = apiAmazonService.getAmazonSalesTrafficReport(insertLogId, AMAZON_SYSTEM_NAME, type, queryParams);
            if (apiResponse.getCode() == 500){
                apiLogService.updateApiLog(insertLogId, AMAZON_SYSTEM_NAME, type, "queryParams：" + JSON.toJSONString(queryParams), "ECP_API定时获取亚马逊店铺商品价格报表信息出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
        }catch (Exception ex){
            logger.error("ECP_API定时获取亚马逊店铺商品销售流量报表信息出错，错误信息为：" + ex.getMessage());
        }
    }

    /**
     * 统一获取2年内的订单数据
     */
    public void getAmazonOrder3()
    {
        System.out.println("测试数据!");
        for (int j = 2023; j <= 2023; j++) {
            for (int i = 1; i <= 2; i++) {
                //获取当年的12个月份
                Date firstDayOfMonth = getFirstDayOfMonth(j + "", i + "");
                Date lastDayOfMonth = getLastDayOfMonth(j + "", i + "");
                Calendar calendar = new GregorianCalendar();
                calendar.add(Calendar.DATE, 0);//每天9点钟运行时，取当前时间之前1天的数据
                calendar.set(Calendar.MILLISECOND, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.HOUR, 0);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                try {
                    String type = "GetAmazonOrderInfo3";
                    Map<String, Object> queryParams = new HashMap<>();
                    queryParams.put("authorizeState", "已授权");
                    Date startTime = firstDayOfMonth;
                    Date endTime = lastDayOfMonth;
                    int insertLogId = apiLogService.addApiLog(j+"年"+i+"月", type, "定时获取任务获取亚马逊订单信息，条件queryParams：" + JSON.toJSONString(queryParams), "", 0, "");
                    boolean variable = true;
                    while (variable) {
                        Thread.sleep(25000L);
                        ApiResponse apiResponse = apiAmazonService.getAllAmazonOrderInfo(insertLogId, j+"年"+i+"月", type, queryParams, startTime, 3, endTime);
                        if (apiResponse.getCode() == 500) {
                            variable = false;
                            apiLogService.updateApiLog(insertLogId, j+"年"+i+"月", type, "定时获取任务获取亚马逊订单信息，条件queryParams：" + JSON.toJSONString(queryParams), "ECP_API定时获取亚马逊店铺订单出错[取前一天数据]，错误为：" + apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
                        }else if (apiResponse.getCode() == 300) {
                            logger.info("等待中,执行正在继续"+j+"年"+i+"月");
                        } else {
                            variable = false;
                        }
                    }


                } catch (Exception ex) {
                    logger.error("ECP_API定时获取亚马逊店铺订单出错[取前一天数据]，错误信息为：" + ex.getMessage());
                }
                if (lastDayOfMonth.compareTo(calendar.getTime()) == 1) {
                    return;
                }
            }
        }

    }

    //获取目标年份中目标月的第一天的开始时间
    public static Date getFirstDayOfMonth(String year,String month) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        final Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR,Integer.parseInt(year));
        cal.set(Calendar.MONTH,Integer.parseInt(month)-1);
        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);
        //获取目标月和目标年份的当月第一天时间
        final int start =Calendar.YEAR;
        cal.set(Calendar.DAY_OF_MONTH, start);
        System.out.println("开始时间:" + sdf1.format(cal.getTime()));
        return cal.getTime();
    }
    //获取目标年份中目标月的最后一天
    public static Date getLastDayOfMonth(String year,String month) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR,Integer.parseInt(year));
        cal.set(Calendar.MONTH,Integer.parseInt(month)-1);
        cal.set(Calendar.HOUR_OF_DAY,23);
        cal.set(Calendar.MINUTE,59);
        cal.set(Calendar.SECOND,59);
        //获取目标月和目标年份的当月第一天时间
        final int start =Calendar.YEAR;
        final int last = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        cal.set(Calendar.DAY_OF_MONTH, last);
        System.out.println("结束时间:" + sdf1.format(cal.getTime()));
        return cal.getTime();
    }
}
